package com.lyf.core.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.lyf.core.pojo.User;

@Repository
public interface UserDao {

	@Select("select t1.* , t2.department_name as dept_name , get_user_rolenames(t1.id) as role_name "
		+ " from ma_user as t1	left join ma_department as t2" 
		+ " on t1.dept_id = t2.did "
		+ " where t1.user_id =#{user_id}" )
	public User findByUserId(@Param("user_id") String user_id);
	
	@Select("select t1.* , t2.department_name as dept_name , get_user_rolenames(t1.id) as role_name "
			+ " from ma_user as t1	left join ma_department as t2" 
			+ " on t1.dept_id = t2.did "
			+ " where t1.id =#{id}" )
	public User findById(@Param("id") int id);
	
	@Insert("insert into ma_user(user_id , user_name,user_pass,dept_id,description,roles) "
			+ " values (#{u.user_id} , #{u.user_name} ,#{u.user_pass},#{u.dept_id},#{u.description},#{u.roles})")
	@Options(useGeneratedKeys=true,keyColumn="id" ,keyProperty="u.id")
	public void insert(@Param("u") User u);
	
	@Delete("delete from ma_user where id = #{id}")
	public void delete(@Param("id") int id);
	
	@Update("update ma_user set user_pass=#{pass} where id=#{id}")
	public void resetPass(@Param("id")int id ,@Param("pass") String pass);
	
	@Update("update ma_user set user_name = #{u.user_name} , dept_id =#{u.dept_id},roles=#{u.roles},description=#{u.description} where id = #{u.id}")
	public void updateUser(@Param("u") User u);
	
	@Select({"<script>",  
		"select count(1) from ma_user as t where 1 = 1" , 
		"<when test='key != null  '> " ,
			" and user_name ~ #{key}" ,
		"</when>" ,
		"<when test='deptId != null  '> " ,
			" and dept_id =any(get_all_childs_did(#{deptId}))" ,
		"</when>" ,
		  
		"</script>"
	})
	public int findUserSize(@Param("deptId") Integer deptId , @Param("key") String key);
	
	@Select({"<script>",  
		"select t1.* , t2.department_name as dept_name , get_user_rolenames(t1.id) as role_name "
		+ " from ma_user as t1	left join ma_department as t2",
		" on t1.dept_id = t2.did " ,
		" where 1 = 1 " , 
		"<when test='key != null  '> " ,
			" and ( t1.user_name ~ #{key} or user_id ~ #{key})" ,
		"</when>" ,
		"<when test='deptId != null  '> " ,
			" and t1.dept_id =any(get_all_childs_did(#{deptId}))" ,
		"</when>" ,
		" order by t1.id limit #{rows} offset (#{page}-1) * #{rows} " ,
		"</script>"
	})
	public List<User> findUserList(@Param("deptId") Integer deptId , @Param("key")String key ,@Param("rows") int rows ,@Param("page") int page);
	
 
	
}
